-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
29 lines (21 loc) · 867 Bytes
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def knapsack(W, weights, values, n):
dp = [[0 for _ in range(W + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, W + 1):
if weights[i - 1] <= w:
dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w])
else:
dp[i][w] = dp[i - 1][w]
return dp[n][W]
if __name__ == "__main__":
n = int(input("Enter the number of items: "))
weights = []
values = []
print("Enter the weights and values of the items:")
for i in range(n):
weight = int(input(f"Item {i + 1} - Weight: "))
value = int(input(f"Item {i + 1} - Value: "))
weights.append(weight)
values.append(value)
W = int(input("Enter the capacity of the knapsack: "))
print(f"Maximum value in knapsack: {knapsack(W, weights, values, n)}")